package com.example.chengma.service.impl;

import com.example.chengma.dao.repostory.IcommentRepostory;
import com.example.chengma.pojo.vo.CommentVO;
import com.example.chengma.pojo.vo.JsonResultVO;
import com.example.chengma.service.ICommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CommentServiceImpl implements ICommentService {
    @Autowired
    IcommentRepostory commentRepostory;
    @Override
    public List<JsonResultVO> selectJsonResultVO(int qid) {
        List<CommentVO> commentVOS = commentRepostory.selectCommentVOByQuestionId(qid);
        System.out.println(commentVOS);
        HashMap<Integer,Integer>hashMapid = new HashMap<>();
        HashMap<Integer,JsonResultVO>hashMapVO = new HashMap<>();
        for(int i = 0;i<commentVOS.size();i++){
            JsonResultVO jsonResultVO = new JsonResultVO();
            BeanUtils.copyProperties(commentVOS.get(i),jsonResultVO);
            Integer collectCount = commentRepostory.selectCollectedCountByCommentId(jsonResultVO.getId());
            Integer likeCount = commentRepostory.selectLikedCountByCommentId(jsonResultVO.getId());
            jsonResultVO.setCollectedCount(collectCount);
            jsonResultVO.setLikeCount(likeCount);
            hashMapid.put(jsonResultVO.getId(),jsonResultVO.getReplyId());
            hashMapVO.put(jsonResultVO.getId(),jsonResultVO);
        }
        ArrayList<JsonResultVO>list = new ArrayList<>();
        Set<Map.Entry<Integer, Integer>> entries = hashMapid.entrySet();
        for(Map.Entry<Integer,Integer> entry:entries){
            Integer value = entry.getValue();
            if(value == 0 ){
                Integer key = entry.getKey();
                list.add(hashMapVO.get(key));
            }else{
                Integer key = entry.getKey();
                JsonResultVO jsonResultVOUp = hashMapVO.get(value);
                JsonResultVO jsonResultVODown = hashMapVO.get(key);
                jsonResultVOUp.setRepliedCount(jsonResultVOUp.getRepliedCount()+1);
                jsonResultVOUp.getChildren().add(jsonResultVODown);

            }
        }


        return list;
    }
}
